package com.xiaocz.hblsubstitutedriving.base;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;
import com.amap.api.location.AMapLocation;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.gyf.barlibrary.ImmersionBar;
import com.umeng.analytics.MobclickAgent;
import com.vise.log.ViseLog;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.widgets.load.core.LoadManager;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.model.SocketModel;
import com.xiaocz.hblsubstitutedriving.model.UserInfo;
import com.xiaocz.hblsubstitutedriving.model.VersionUpdate;
import com.xiaocz.hblsubstitutedriving.utils.Constants;
import com.xiaocz.hblsubstitutedriving.widget.EmptyView;
import com.xiaocz.hblsubstitutedriving.widget.ErrorView;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * BaseActivity基类的定义
 */

public abstract class BaseActivity extends Activity {

    // 定义标题栏对象
    protected Toolbar mToolbar;


    @Override
    protected void initWidgets() {
        super.initWidgets();
        // 初始化标题栏对象
        initToolbar((Toolbar) findViewById(R.id.toolbar), findViewById(R.id.top_view));
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 初始化Toolbar标题栏
     *
     * @param toolbar Toolbar
     */
    public void initToolbar(Toolbar toolbar, View top_view) {
        mToolbar = toolbar;
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
        if (top_view != null) {
            ImmersionBar.setTitleBar(this, top_view);
        }
        initTitleNeedBack();
    }

    /**
     * 设置Toolbar标题栏的显示属性
     */
    protected void initTitleNeedBack() {
        // 设置左上角的返回按钮为实际的返回效果
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // 设置显示返回按钮
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            // 设置不显示标题栏的title
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    public <T> RspModel<T> getAnalysis(AsyncHttpResponse response, Type type, String log) {
        ViseLog.d(getClass().getSimpleName() + ":" + response.toString());
        switch (response.getCode()) {
            case 200:
                try {
                    RspModel<T> rspModel = new Gson().fromJson(response.getBody(), type);
                    ViseLog.e(log + rspModel.toString());
                    return rspModel;
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                break;
            default:
                App.getInstance().showMessage(getString(R.string.service_error));
                break;
        }
        return null;
    }


    /**
     * 数据解析
     *
     * @param response 数据源
     * @param type     class
     * @param log      log
     * @param <T>      泛型
     * @return 结果
     */
    public <T> RspModel<T> getAnalysisBase(LoadManager mLoadManager, AsyncHttpResponse response, Type type, String log) {
        ViseLog.d(response.toString());
        switch (response.getCode()) {
            case 200:
                try {
                    RspModel<T> rspModel = new Gson().fromJson(response.getBody(), type);
                    ViseLog.e(log + rspModel.toString());
                    switch (rspModel.getCode()) {
                        case 200:
                            mLoadManager.showSuccessView();
                            return rspModel;
                        default:
                            App.getInstance().showMessage(rspModel.getMessage());
                            mLoadManager.showStateView(EmptyView.class);
                            break;
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    mLoadManager.showStateView(ErrorView.class);
                }
                break;
            default:
                mLoadManager.showStateView(EmptyView.class);
                break;
        }
        return null;
    }

    /**
     * 获取socket地址
     */
    public void getSocket(String provinceName, String cityName) {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("province_name", provinceName);
        asyncHttpPostFormData.addFormData("city_name", cityName);
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/getSocketAddress", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<SocketModel>>() {
                }.getType();
                RspModel<SocketModel> rspModel = getAnalysis(response, type, "获取socket地址");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus()) {
                            SocketModel socketModel = rspModel.getData();
                            Constants.TCP_IP = socketModel.getSocketip();
                            Constants.TCP_PORT = socketModel.getSocketport();
                        } else {
                            App.getInstance().showMessage("正在连接订单推送系统中");
                        }
                        break;
                }
            }
        });
    }

    /**
     * 版本更新
     */
    public void getUpdateVersion() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        okHttpClient.post(Common.Constant.API_IP + "api/Common/getUpdateInfo", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<VersionUpdate>>() {
                }.getType();
                RspModel<VersionUpdate> rspModel = getAnalysis(response, type, "版本更新");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        try {
                            int versionCode = getVersionCode();
                            if (rspModel.getData().getVersion() > versionCode) {
                                updateVersion(rspModel.getData().getIs_forced(), "是否更新?", rspModel.getData().getDescription(), rspModel.getData().getApk_url());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }
        });
    }

    private void updateVersion(int force, String title, String content, String url) {
        DownloadBuilder downloadBuilder = AllenVersionChecker.getInstance().downloadOnly(
                UIData.create().setTitle(title).setContent(content).setDownloadUrl(url)
        );
        downloadBuilder.setSilentDownload(false); //默认false
        downloadBuilder.setForceRedownload(true); //默认false 本地有安装包缓存也会重新下载apk
        downloadBuilder.executeMission(mContext);
        //强制更新
        if (force == 1) {
            //是否显示下载对话框
            downloadBuilder.setShowDownloadingDialog(true);// 默认true
            downloadBuilder.setForceUpdateListener(new ForceUpdateListener() {
                @Override
                public void onShouldForceUpdate() {
                }
            });
        } else {
            downloadBuilder.setShowDownloadingDialog(false);// 默认true
        }
    }

    /**
     * 拨打电话的操作，并关闭当前dialog
     */
    public void callPhone(String tel) {
        if (TextUtils.isEmpty(tel)) {
            UserInfo info = new Gson().fromJson(AccountManagers.getAccount(), UserInfo.class);
            if (info != null) {
                tel = info.getSiguan_phone();
            }
        }
        // 跳转到拨号界面，同时传递电话号码
        if (!TextUtils.isEmpty(tel)) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
            startActivity(intent);
        }
    }
}
